package com.qf.controller;

import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.qf.pojo.Order;
import com.qf.pojo.R;
import com.qf.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.print.attribute.standard.PrinterURI;
import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;

//@RestController
//@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    //服务发现客户端
    private DiscoveryClient discoveryClient;

    //定义轮询的标记值
    private AtomicInteger ai = new AtomicInteger(0);

    //引入ribbon负载均衡器依赖后，可以直接注入一个负载均衡器对象
    @Autowired  //实际注入的是RibbonLoadBalanceClient
    private LoadBalancerClient loadBalancerClient;

    @GetMapping("/{id}")
    public R findOrders(@PathVariable("id") Integer id) throws InterruptedException {

/*
        //根据指定的服务名称，获取这个名称对应的服务列表
        List<ServiceInstance> instances = discoveryClient.getInstances("QF-ORDER");
//        ServiceInstance serviceInstance = instances.get(0);

        //模拟随机负载均衡
//        int idx = new Random().nextInt(instances.size()); //[0,2)
//        ServiceInstance serviceInstance = instances.get(idx);

        //模拟轮询负载均衡 (AtomicInteger可以保证自增的原子性 - 内部通过cas实现的（乐观锁）)
        int andIncrement = ai.getAndIncrement(); //0，1，2，3，4，5....
        int idx = andIncrement % instances.size(); //0,1,0,1....
        ServiceInstance serviceInstance = instances.get(idx);*/

/*
        //利用负载均衡器客户端实现负载均衡
        ServiceInstance serviceInstance = loadBalancerClient.choose("QF-ORDER");

        String host = serviceInstance.getHost();
        int port = serviceInstance.getPort();

        R r = restTemplate.getForObject("http://"+host+":"+port+"/order/" + id, R.class);*/

        R r = restTemplate.getForObject("http://QF-ORDER/order/" + id, R.class);
        return r;
    }
}
